﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.SpecializedProperties;
using EPiServer.Web;

namespace EPiBoost.Core.Extensions
{
	public static class UrlExtensions
	{
		public static string GetHref(this Url url)
		{
			if (url != null)
			{
				var page = GetPage(url);
				if (page != null)
				{
					return page.GetHref();
				}
				string urlString = url.ToString();
				if (urlString[0] == '~' && HttpContext.Current != null)
				{
					return System.Web.Mvc.UrlHelper.GenerateContentUrl(urlString, new HttpContextWrapper(HttpContext.Current));
				}
				return urlString;
			}
			return null;
		}

		public static PageData GetPage(this Url url)
		{
			PageData result;
			TryParseToPageData(url, out result);
			return result;
		}


		public static bool TryParseToPageData(this Url url, out PageData result)
		{
			if (url != null)
			{
				return TryParseToPageData(url.ToString(), out result, null);
			}
			result = null;
			return false;
		}

		/// <summary>
		/// Tries to parse a LinkItem to a PageData object
		/// </summary>
		/// <param name="self">LinkItem object</param>
		/// <param name="result">The PageData object if it can be parsed - otherwise null</param>
		/// <param name="languageBranch">The language code to return page data's from</param>
		/// <returns>If the LinkItem can be parsed to PageData</returns>
		internal static bool TryParseToPageData(string url, out PageData result, string languageBranch)
		{
			result = null;

			Guid guid = PermanentLinkUtility.GetGuid(url);

			if (guid == Guid.Empty)
			{
				return false;
			}
			else
			{
				try
				{
					PageReference pRef = PermanentLinkUtility.FindPageReference(guid);
				  var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
					if (languageBranch != null)
					{

						//result = DataFactory.Instance.GetPage(pRef, new LanguageSelector(languageBranch));
						result = repo.Get<PageData>(pRef, new LanguageSelector(languageBranch));

						if (result == null)
							return false;
					}
					else
					{
						//result = DataFactory.Instance.GetPage(pRef);
						result = repo.Get<PageData>(pRef);
					}
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}
		}



	}
}
